import hashlib
import logging
import time

import jwt

from libs.common import MD5

logger = logging.getLogger(__name__)

SECRET_KEY = 'olqiz103ppbixad5'
FIXED_HEADER = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.'
ALG = 'HS512'


def jwt_encode(cashier_id, shop_id):
    now = int(time.time())
    exp = now + 86400 * 365
    token = jwt.encode({'cashier_id': cashier_id, 'shop_id': shop_id, 'exp': exp}, SECRET_KEY, algorithm=ALG)
    token = token.replace(FIXED_HEADER, '')
    return token


def jwt_decode(token):
    payload = {}
    encoded = FIXED_HEADER + token
    try:
        decode_value = jwt.decode(encoded, SECRET_KEY, algorithms=ALG)
        payload = {
            'cashier_id': decode_value['cashier_id'],
            'shop_id': decode_value['shop_id'],
        }
    except Exception as e:
        logger.error(e)
    return payload


def generate_password(pwd, salt):
    return MD5(pwd + salt)


def make_member_password(password):
    sha1 = hashlib.sha1()
    hash_md5 = hashlib.md5(password.encode('utf-8'))
    md5 = hash_md5.hexdigest()
    sha1.update(md5.encode('utf-8'))
    hashcode = sha1.hexdigest()  # 获取加密串
    logging.info(hashcode)
    return hashcode
